<template>
  <a-row :style="{ width: '752px', minHeight: '520px' }">
    <a-col :span="7">
      <div class="float-left">
        <TreeCategory
          :selected="[]"
          type="no-cate"
          :text="label"
          @update="handleCategoryUpdate"
        />
      </div>
    </a-col>
    <a-col :span="17">
      <a-row :style="{ marginBottom: '24px', paddingLeft: '10px' }">
        <div class="float-left j-b-flex">
          <div class="d-flex"></div>
          <div class="d-flex">
            <div class="d-flex mr-24">
              <a-typography-text>名称：</a-typography-text>
              <a-input
                v-model:value="title"
                allow-clear
                :style="{ width: '160px' }"
                placeholder="请输入名称关键字"
                @change="handleTitleChange"
              />
            </div>
            <div class="d-flex">
              <a-button class="mr-16" @click="resetVideoList">重置</a-button>
              <a-button type="primary" @click="handleQuery">查询</a-button>
            </div>
          </div>
        </div>
      </a-row>

      <div v-if="init" class="float-left text-center mt-30">
        <a-spin></a-spin>
      </div>

      <div 
        class="video-list" 
        :style="{ display: init ? 'none' : 'block' }"
      >
        <div v-if="videoList.length === 0 && !init">
          <a-col :span="24" :style="{ marginTop: '150px' }">
            <a-empty description="暂无视频" />
          </a-col>
        </div>

        <div v-else-if="videoList.length > 0" class="list-select-column-box c-flex">
          <a-table
            :row-selection="rowSelection"
            :columns="columns"
            :data-source="videoList"
            :loading="loading"
            :pagination="paginationProps"
            :row-key="(record: any) => record.id"
          />
        </div>
      </div>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { ref, watch, computed, h, onMounted } from 'vue';
import { Typography } from 'ant-design-vue';
import { resource } from '@/api';
import DurationText from './duration-text.vue';
import TreeCategory from './tree-category.vue';

interface VideoItem {
  id: number;
  name: string;
  created_at: string;
  type: string;
  url: string;
  path: string;
  size: number;
  extension: string;
  admin_id: number;
}

interface Props {
  defaultCheckedList: any[];
  label: string;
  open: boolean;
  onSelected: (arr: any[], videos: any[]) => void;
}

const props = defineProps<Props>();

const { Text: ATypographyText } = Typography;

const init = ref(true);
const category_ids = ref<any[]>([]);
const loading = ref(false);
const videoList = ref<VideoItem[]>([]);
const videosExtra = ref<any>({});
const page = ref(1);
const size = ref(10);
const total = ref(0);
const selectedRowKeys = ref<number[]>([]);
const title = ref('');
const requestTimer = ref<NodeJS.Timeout>();

// 获取所有已选中的键（包括默认选中的和当前选中的）
const allSelectedKeys = computed(() => {
  // 合并默认选中的和当前选中的，去重
  const allKeys = [...new Set([...props.defaultCheckedList, ...selectedRowKeys.value])];
  return allKeys;
});

// 防抖的视频列表获取函数
const getVideoList = async () => {
  if (!props.open) return;
  
  if (requestTimer.value) {
    clearTimeout(requestTimer.value);
  }
  
  requestTimer.value = setTimeout(async () => {
    loading.value = true;
    try {
      const categoryIds = category_ids.value.join(',');
      
      const res: any = await resource.resourceList(
        page.value, 
        size.value, 
        '', 
        '', 
        title.value, 
        'VIDEO', 
        categoryIds
      );
      
      if (res?.data) {
        total.value = res.data.result?.total || 0;
        videosExtra.value = res.data.videos_extra || {};
        videoList.value = res.data.result?.data || [];
      } else {
        videoList.value = [];
        total.value = 0;
        videosExtra.value = {};
      }
    } catch (err) {
      videoList.value = [];
      total.value = 0;
      videosExtra.value = {};
    } finally {
      loading.value = false;
      init.value = false;
    }
  }, 300);
};

// 组件挂载时立即加载数据
onMounted(() => {
  if (props.open) {
    getVideoList();
  }
});

// 监听props.open变化
watch(() => props.open, (newVal) => {
  if (newVal) {
    init.value = true;
    getVideoList();
    // 打开时重置当前选中状态，但保留默认选中
    selectedRowKeys.value = [];
  } else {
    videoList.value = [];
    videosExtra.value = {};
    total.value = 0;
    selectedRowKeys.value = [];
  }
}, { immediate: true });

// 监听defaultCheckedList变化
watch(() => props.defaultCheckedList, (newVal) => {
  // 这里不需要更新selectedRowKeys，因为allSelectedKeys计算属性会自动处理
}, { immediate: true });

// 监听其他参数变化
watch([category_ids, page, size], () => {
  if (props.open) {
    getVideoList();
  }
});

// 重置列表
const resetVideoList = () => {
  page.value = 1;
  title.value = '';
  category_ids.value = [];
  getVideoList();
};

// 查询
const handleQuery = () => {
  page.value = 1;
  getVideoList();
};

// 标题变化
const handleTitleChange = (e: Event) => {
  title.value = (e.target as HTMLInputElement).value;
};

// 分类更新
const handleCategoryUpdate = (keys: any[]) => {
  category_ids.value = keys;
  page.value = 1;
  getVideoList();
};

// 分页配置
const paginationProps = computed(() => ({
  current: page.value,
  pageSize: size.value,
  total: total.value,
  onChange: (p: number, ps: number) => {
    page.value = p;
    size.value = ps;
  },
  showSizeChanger: true,
}));

// 表格列配置
const columns = computed(() => [
  {
    title: '视频',
    key: 'name',
    customRender: ({ record }: { record: VideoItem }) => {
      return h('div', { class: 'd-flex' }, [
        h('i', {
          class: 'iconfont icon-icon-video',
          style: {
            fontSize: '14px',
            color: 'rgba(0,0,0,0.3)',
          }
        }),
        h('div', { class: 'video-title ml-8' }, record.name)
      ]);
    },
  },
  {
    title: '时长',
    key: 'duration',
    customRender: ({ record }: { record: VideoItem }) => {
      return h(DurationText, {
        duration: videosExtra.value[record.id]?.duration || 0
      });
    },
  },
]);

// 修复选中逻辑 - 与UploadCoursewareSub保持一致
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: any[], selectedRows: any[]) => {
    selectedRowKeys.value = keys;
    
    // 构建视频数据数组
    const arrVideos = selectedRows.map(row => ({
      name: row.name,
      type: row.type,
      rid: row.id,
      duration: videosExtra.value[row.id]?.duration || 0,
    }));
    
    // 传递当前选中的键和视频数据给父组件
    props.onSelected(keys, arrVideos);
  },
  getCheckboxProps: (record: any) => ({
    // 关键修复：禁用所有已经选中的项目（包括默认选中的）
    disabled: allSelectedKeys.value.includes(record.id),
  }),
}));

</script>

<style scoped>

</style>